package com.landun.market.service.impl;

import com.landun.market.exception.BusinessException;
import com.landun.market.pojo.enums.StateCode;
import com.landun.market.pojo.model.Category;
import com.landun.market.pojo.model.Price;
import com.landun.market.repository.ICategoryRepository;
import com.landun.market.repository.IPriceRepository;
import com.landun.market.service.IPriceService;
import com.landun.market.util.FinanceUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Created by yi.zhao on 2018/5/19.
 */
@Service
public class PriceService implements IPriceService {
    @Autowired
    private IPriceRepository priceRepository;
    @Autowired
    private ICategoryRepository categoryRepository;


    @Override
    public boolean importDraft(Date priceDate, InputStream excelInputStream) throws Exception {
        priceRepository.deleteByDateAndState(priceDate, StateCode.INACTIVE);
        Workbook workbook = WorkbookFactory.create(excelInputStream);
        Sheet sheet = workbook.getSheetAt(0);
        if (!this.checkTemplate(sheet)) {
            throw new BusinessException("模板错误,请用标准价格导入模板!");
        }
        List<Category> categories = categoryRepository.findAll(StateCode.ACTIVE.code());
        Map<String, Category> stringCategoryMap = categories.stream().collect(Collectors.toMap(Category::getName, Function.identity(), (a, b) -> a));

        //---------循环行-----------
        Set<Price> set = new HashSet<>();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (null == row) {
                continue;
            }
            Price price = convert(row, stringCategoryMap);
            price.setPriceDate(priceDate);
            set.add(price);
        }

        try {
            priceRepository.create(set.toArray(new Price[set.size()]));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<Price> getDraft(Date priceDate, Category category) {
        return priceRepository.findByCategoryDateAndState(category.getId(), priceDate
                , StateCode.INACTIVE);
    }

    @Override
    public boolean publish(Date priceDate) {
        try {
            priceRepository.deleteByDateAndState(priceDate, StateCode.ACTIVE);
            priceRepository.updateStateByDate(priceDate, StateCode.ACTIVE);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public List<Price> getPublished(Date priceDate, Category category) {
        return priceRepository.findByCategoryDateAndState(category == null ? null : category.getId(), priceDate
                , StateCode.ACTIVE);
    }

    @Override
    public boolean update(Price price) {
        try {
            priceRepository.update(price);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 校验Excel模板
     */
    private boolean checkTemplate(Sheet sheet) {
        /*Row row = sheet.getRow(2);
        if(row != null){
            List<String> tempTitleList = ExcelUtil.genInspireUserExcelTitle(list);
            List<String> titleList = ExcelUtil.getInspireUserSheetTitle(row);
            if(titleList.size() > 0) {
                if (titleList.contains(CHECK_RESULT)) {
                    titleList.remove(CHECK_RESULT);
                }
                if (titleList.contains(CHECK_MEMO)) {
                    titleList.remove(CHECK_MEMO);
                }
                if (titleList.size()>=tempTitleList.size()){
                    String[] template = tempTitleList.toArray(new String[0]);
                    String[] excel = titleList.toArray(new String[0]);
                    for(int i=0;i<tempTitleList.size();i++){
                        if(!excel[i].equals(template[i])){
                            return false;
                        }
                    }
                    return true;
                }
            }
        }*/
        return true;
    }

    private List<String> getExcelSheetTitle(Row row) {
        return null;
    }

    private Price convert(Row row, Map<String, Category> stringCategoryMap) throws Exception {
        Price price = new Price();
        int i = 0;
        price.setCategoryId(stringCategoryMap.get(row.getCell(i++).getStringCellValue()).getId());
        price.setName(row.getCell(i++).getStringCellValue());
        price.setArea(row.getCell(i++).getStringCellValue());
        price.setUnit(row.getCell(i++).getStringCellValue());
        price.setMinSellingPrice(FinanceUtils.getSysPrice(String.valueOf(row.getCell(i++).getNumericCellValue())));
        price.setMaxSellingPrice(FinanceUtils.getSysPrice(String.valueOf(row.getCell(i++).getNumericCellValue())));
        price.setWholesalePrice(FinanceUtils.getSysPrice(String.valueOf(row.getCell(i++).getNumericCellValue())));
        price.setReferencePrice(FinanceUtils.getSysPrice(String.valueOf(row.getCell(i++).getNumericCellValue())));
        price.setState(StateCode.INACTIVE);
        return price;
    }
}
